package com.sx.gongzhong.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.sx.gongzhong.BaseActivity;
import com.sx.gongzhong.MyApplication;
import com.sx.gongzhong.R;
import com.sx.gongzhong.model.SplashBean;
import com.sx.gongzhong.model.UserInfoBean;
import com.sx.gongzhong.net.ServiceFactory;
import com.sx.gongzhong.pest.SplashPest;
import com.sx.gongzhong.utils.BaseUtil;
import com.sx.gongzhong.utils.Global;
import com.sx.gongzhong.utils.InitData;
import com.sx.gongzhong.utils.NetworkUtils;
import com.sx.gongzhong.utils.ToastUtils;
import com.sx.gongzhong.view.SplashView;

import butterknife.BindView;
import butterknife.ButterKnife;
import xiaofei.library.datastorage.DataStorageFactory;
import xiaofei.library.datastorage.IDataStorage;

public class SplashActivity extends BaseActivity implements SplashView {

    @BindView(R.id.iv_splash)
    ImageView ivSplash;

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);
        setGoneTitle();
        new SplashPest(this).getSplashData();
    }

    @Override
    public void showError(String message) {
        ivSplash.setImageResource(R.mipmap.splash);
        initData();
    }

    @Override
    public void getSplashDataSuccess(SplashBean data) {
        if (data != null && data.getPhotoBean() != null){
            if (data.getPhotoBean() != null && !BaseUtil.isEmpty(data.getPhotoBean().getPath())){
                Glide.with(this).load(ServiceFactory.getUrl(data.getPhotoBean().getPath())).into(ivSplash);
            }else {
                ivSplash.setImageResource(R.mipmap.splash);
            }
        }else {
            ivSplash.setImageResource(R.mipmap.splash);
        }
        initData();
    }

    /**
     * 初始话数据
     */
    private void initData() {
        IDataStorage dataStorage = DataStorageFactory.getInstance(
                getApplicationContext(), DataStorageFactory.TYPE_DATABASE);
        if (dataStorage.contains(UserInfoBean.class, getPackageName())) {
            UserInfoBean userBean = dataStorage.load(UserInfoBean.class, getPackageName());
            MyApplication.instance.userBean = userBean;
        }
        new Handler().postDelayed(runnableMain, 3000);//进入主页
        if (NetworkUtils.getNetWorkState(this) == Global.NETWORK_NONE) {
            ToastUtils.showToast(this, "当前网络连接异常");
        } else {
            new InitData(this).loadData();
        }
    }
    private Runnable runnableMain = new Runnable() {
        @Override
        public void run() {
            startActivity(new Intent(SplashActivity.this, MainActivity.class));
            finish();
        }
    };
}
